package com.joysuch.wwyt.datasync.service.impl;

import com.joysuch.wwyt.datasync.support.AopDataSyncDaoInterceptor;
import com.joysuch.wwyt.datasync.util.DataSyncUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.PostConstruct;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通用的数据同步条件，将符合条件的表写入数据库
 */
@Component
@Slf4j
@ConditionalOnProperty(value = "wwyt.feature.datasync.customer", havingValue = "common")
public class CommonDataSyncCondition extends  BaseDataSyncCondition{

    @Value("${wwyt.feature.datasync.enabled-table-pattern}")
    private String enabledTablePattern;
    @Value("${wwyt.feature.datasync.disabled-table-pattern}")
    private String disabledTablePattern;

    private List<String> enabledPatternList = new ArrayList<>();
    private List<String> disabledPatternList = new ArrayList<>();

    // 缓存表名映射和判断结果
    private ConcurrentHashMap<Class, String> tableNameMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, Boolean> shouldSyncMap = new ConcurrentHashMap<>();

    @Override
    public boolean shouldSync(AopDataSyncDaoInterceptor.Info info) {
        if(enabledPatternList.isEmpty()) {
            return false;
        }
        String tableName = getTableName(info.getDomainClass());

        return shouldSyncMap.computeIfAbsent(tableName, name -> {
            AntPathMatcher matcher = new AntPathMatcher();
            if(!disabledPatternList.isEmpty()) {
                for(String s : disabledPatternList) {
                    if(matcher.match(s, name)) {
                        log.debug("table#{} disabled", name);
                        return false;
                    }
                }
            }
            for(String s : enabledPatternList) {
                if(matcher.match(s, name)) {
                    log.debug("table#{} enabled", name);
                    return true;
                }
            }
            return false;
        });
    }

    @PostConstruct
    public void loadRegisterInfo() {
        if(enabledTablePattern != null) {
            String[] split = enabledTablePattern.split("\\s*,\\s*");
            for(String s : split) {
                if(StringUtils.isNoneBlank(s)) {
                    enabledPatternList.add(s);
                }
            }
        }
        if(disabledTablePattern != null) {
            String[] split = disabledTablePattern.split("\\s*,\\s*");
            for(String s : split) {
                if(StringUtils.isNoneBlank(s)) {
                    disabledPatternList.add(s);
                }
            }
        }
    }

    @Override
    public String getServiceName(AopDataSyncDaoInterceptor.Info info, Object entity, Object id) {
          // 用表名作为serviceId名字
          return getTableName(info.getDomainClass());
    }

    private String getTableName(Class domainClass) {
        return tableNameMap.computeIfAbsent(domainClass, key -> {
            String name = DataSyncUtils.getTableName(key);
            if(name != null) {
                return name.toLowerCase();
            }
            return null;
        });
    }
}
